import { useState } from 'react'
import { useState } from 'react'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism'
import * as curlconverter from 'curlconverter'
import './App.css'

// 增强的 curl 命令解析器，支持更多参数
const parseCurlCommand = (curl) => {
  const result = {
    url: '',
    method: 'GET',
    headers: {},
    data: null,
    cookies: {},
    params: {},
    files: {},
    auth: null,
    isJson: false,
    isForm: false,
    isMultipart: false
  };
  
  // 清理命令，移除多余空格和换行
  curl = curl.replace(/\\\s*\n/g, ' ').replace(/\s+/g, ' ').trim();
  
  // 提取 URL - 支持多种格式
  const urlPatterns = [
    /https?:\/\/[^\s'"]+/,
    /'(https?:\/\/[^']+)'/,
    /"(https?:\/\/[^"]+)"/,
    /(?:^|\s)([a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.)+[a-zA-Z]{2,}(?:\/[^\s]*)?/
  ];
  
  for (const pattern of urlPatterns) {
    const match = curl.match(pattern);
    if (match) {
      result.url = match[1] || match[0];
      break;
    }
  }
  
  if (!result.url) {
    result.url = 'https://example.com';
  }
  
  // 确保URL有协议
  if (result.url && !result.url.match(/^https?:\/\//)) {
    result.url = 'http://' + result.url;
  }
  
  // 解析 HTTP 方法
  const methodPatterns = [
    /-X\s+([A-Z]+)/i,
    /--request\s+([A-Z]+)/i
  ];
  
  for (const pattern of methodPatterns) {
    const match = curl.match(pattern);
    if (match) {
      result.method = match[1].toUpperCase();
      break;
    }
  }
  
  // 解析 Headers
  const headerPatterns = [
    /-H\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g,
    /--header\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g
  ];
  
  for (const pattern of headerPatterns) {
    let match;
    while ((match = pattern.exec(curl)) !== null) {
      const headerLine = match[2];
      const colonIndex = headerLine.indexOf(':');
      if (colonIndex > 0) {
        const key = headerLine.substring(0, colonIndex).trim();
        const value = headerLine.substring(colonIndex + 1).trim();
        result.headers[key] = value;
      }
    }
  }
  
  // 解析 Cookies
  const cookiePatterns = [
    /-b\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g,
    /--cookie\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g
  ];
  
  for (const pattern of cookiePatterns) {
    let match;
    while ((match = pattern.exec(curl)) !== null) {
      const cookieString = match[2];
      // 解析 cookie 字符串 "name1=value1; name2=value2"
      const cookies = cookieString.split(';');
      for (const cookie of cookies) {
        const [name, value] = cookie.split('=').map(s => s.trim());
        if (name && value) {
          result.cookies[name] = value;
        }
      }
    }
  }
  
  // 解析 Basic Auth
  const authPatterns = [
    /-u\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/,
    /--user\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/
  ];
  
  for (const pattern of authPatterns) {
    const match = curl.match(pattern);
    if (match) {
      const [username, password] = match[2].split(':');
      result.auth = { username: username || '', password: password || '' };
      break;
    }
  }
  
  // 解析数据 - 支持多种数据格式
  const dataPatterns = [
    { pattern: /--data-raw\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g, type: 'raw' },
    { pattern: /-d\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g, type: 'data' },
    { pattern: /--data\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g, type: 'data' },
    { pattern: /--data-urlencode\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g, type: 'urlencode' }
  ];
  
  for (const { pattern, type } of dataPatterns) {
    let match;
    while ((match = pattern.exec(curl)) !== null) {
      const data = match[2]; // 获取引号内的内容
      
      if (type === 'urlencode') {
        // 处理 URL 编码数据
        const [key, value] = data.split('=');
        if (key && value !== undefined) {
          result.params[key] = decodeURIComponent(value);
        }
      } else {
        // 普通数据
        if (!result.data) {
          result.data = data;
        } else {
          result.data += '&' + data;
        }
        
        // 检查是否为 JSON
        try {
          JSON.parse(data);
          result.isJson = true;
        } catch (e) {
          // 检查是否为表单数据
          if (data.includes('=') && !data.startsWith('{') && !data.startsWith('[')) {
            result.isForm = true;
            // 解析表单数据到 params
            const pairs = data.split('&');
            for (const pair of pairs) {
              const [key, value] = pair.split('=');
              if (key && value !== undefined) {
                result.params[decodeURIComponent(key)] = decodeURIComponent(value);
              }
            }
          }
        }
      }
    }
  }
  
  // 解析 Form 数据 (-F/--form)
  const formPatterns = [
    /-F\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g,
    /--form\s+(['"])((?:(?!\1)[\s\S]|\\\1)*?)\1/g
  ];
  
  for (const pattern of formPatterns) {
    let match;
    while ((match = pattern.exec(curl)) !== null) {
      const formData = match[2];
      result.isMultipart = true;
      
      if (formData.includes('=@')) {
        // 文件上传
        const [key, filePath] = formData.split('=@');
        result.files[key] = filePath;
      } else if (formData.includes('=')) {
        // 普通表单字段
        const [key, value] = formData.split('=');
        result.params[key] = value;
      }
    }
  }
  
  // 如果有 POST 数据但没有明确指定方法，设置为 POST
  if ((result.data || Object.keys(result.params).length > 0 || Object.keys(result.files).length > 0) && result.method === 'GET') {
    result.method = 'POST';
  }
  
  return result;
};

const simpleCurlConverter = {
  toPython: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = ['import requests'];
    
    // 添加文件处理库（如果需要）
    if (Object.keys(parsed.files).length > 0) {
      lines.push('import os');
    }
    
    // 添加 base64 库（如果有 basic auth）
    if (parsed.auth) {
      lines.push('import base64');
    }
    
    lines.push('');
    
    // 构建 cookies
    if (Object.keys(parsed.cookies).length > 0) {
      lines.push('cookies = {');
      for (const [name, value] of Object.entries(parsed.cookies)) {
        lines.push(`    '${name}': '${value}',`);
      }
      lines.push('}');
      lines.push('');
    }
    
    // 构建 headers
    if (Object.keys(parsed.headers).length > 0) {
      lines.push('headers = {');
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`    '${key}': '${value}',`);
      }
      lines.push('}');
      lines.push('');
    }
    
    // 构建认证
    if (parsed.auth) {
      lines.push(`auth = ('${parsed.auth.username}', '${parsed.auth.password}')`);
      lines.push('');
    }
    
    // 构建数据
    if (parsed.isMultipart && (Object.keys(parsed.files).length > 0 || Object.keys(parsed.params).length > 0)) {
      // Multipart form data
      lines.push('files = {');
      
      // 添加文件
      for (const [key, filePath] of Object.entries(parsed.files)) {
        lines.push(`    '${key}': open('${filePath}', 'rb'),`);
      }
      
      // 添加表单字段
      for (const [key, value] of Object.entries(parsed.params)) {
        lines.push(`    '${key}': (None, '${value}'),`);
      }
      
      lines.push('}');
      lines.push('');
    } else if (parsed.isJson && parsed.data) {
      // JSON 数据
      lines.push('json_data = ' + parsed.data);
      lines.push('');
    } else if (parsed.isForm || Object.keys(parsed.params).length > 0) {
      // 表单数据
      lines.push('data = {');
      for (const [key, value] of Object.entries(parsed.params)) {
        lines.push(`    '${key}': '${value}',`);
      }
      lines.push('}');
      lines.push('');
    } else if (parsed.data) {
      // 原始数据
      lines.push(`data = '${parsed.data}'`);
      lines.push('');
    }
    
    // 构建请求
    const method = parsed.method.toLowerCase();
    let requestLine = `response = requests.${method}('${parsed.url}'`;
    
    const params = [];
    
    // 添加参数
    if (Object.keys(parsed.headers).length > 0) {
      params.push('headers=headers');
    }
    
    if (Object.keys(parsed.cookies).length > 0) {
      params.push('cookies=cookies');
    }
    
    if (parsed.auth) {
      params.push('auth=auth');
    }
    
    // 数据参数
    if (parsed.isMultipart && (Object.keys(parsed.files).length > 0 || Object.keys(parsed.params).length > 0)) {
      params.push('files=files');
    } else if (parsed.isJson && parsed.data) {
      params.push('json=json_data');
    } else if (parsed.isForm || Object.keys(parsed.params).length > 0) {
      params.push('data=data');
    } else if (parsed.data) {
      params.push('data=data');
    }
    
    if (params.length > 0) {
      requestLine += ', ' + params.join(', ');
    }
    requestLine += ')';
    
    lines.push(requestLine);
    
    // 添加文件关闭提示（如果有文件上传）
    if (Object.keys(parsed.files).length > 0) {
      lines.push('');
      lines.push('# 记得关闭文件');
      lines.push('# for file in files.values():');
      lines.push('#     if hasattr(file, "close"):');
      lines.push('#         file.close()');
    }
    
    return lines.join('\n');
  },
  
  toJavaScript: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [];
    
    let fetchCall = `fetch('${parsed.url}'`;
    
    const needsOptions = parsed.method !== 'GET' || 
                        Object.keys(parsed.headers).length > 0 || 
                        Object.keys(parsed.cookies).length > 0 ||
                        parsed.data || 
                        Object.keys(parsed.params).length > 0 ||
                        parsed.auth;
    
    if (needsOptions) {
      fetchCall += ', {';
      lines.push(fetchCall);
      
      if (parsed.method !== 'GET') {
        lines.push(`  method: '${parsed.method}',`);
      }
      
      // 构建 headers
      const allHeaders = { ...parsed.headers };
      
      // 添加 cookies 到 headers
      if (Object.keys(parsed.cookies).length > 0) {
        const cookieString = Object.entries(parsed.cookies)
          .map(([name, value]) => `${name}=${value}`)
          .join('; ');
        allHeaders['Cookie'] = cookieString;
      }
      
      // 添加 basic auth
      if (parsed.auth) {
        const credentials = btoa(`${parsed.auth.username}:${parsed.auth.password}`);
        allHeaders['Authorization'] = `Basic ${credentials}`;
      }
      
      if (Object.keys(allHeaders).length > 0) {
        lines.push('  headers: {');
        for (const [key, value] of Object.entries(allHeaders)) {
          lines.push(`    '${key}': '${value}',`);
        }
        lines.push('  },');
      }
      
      // 添加 body
      if (parsed.isMultipart && (Object.keys(parsed.files).length > 0 || Object.keys(parsed.params).length > 0)) {
        lines.push('  body: (() => {');
        lines.push('    const formData = new FormData();');
        
        for (const [key, value] of Object.entries(parsed.params)) {
          lines.push(`    formData.append('${key}', '${value}');`);
        }
        
        for (const [key, filePath] of Object.entries(parsed.files)) {
          lines.push(`    // formData.append('${key}', fileInput.files[0]); // 请替换为实际文件输入`);
        }
        
        lines.push('    return formData;');
        lines.push('  })(),');
      } else if (parsed.isJson && parsed.data) {
        lines.push(`  body: JSON.stringify(${parsed.data}),`);
      } else if (parsed.isForm || Object.keys(parsed.params).length > 0) {
        const formData = Object.entries(parsed.params)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
          .join('&');
        lines.push(`  body: '${formData}',`);
      } else if (parsed.data) {
        lines.push(`  body: '${parsed.data}',`);
      }
      
      lines.push('})');
    } else {
      lines.push(fetchCall + ')');
    }
    
    lines.push('.then(response => response.json())');
    lines.push('.then(data => console.log(data))');
    lines.push('.catch(error => console.error(error));');
    
    return lines.join('\n');
  },
  
  toNodeAxios: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = ['const axios = require(\'axios\');'];
    
    // 添加文件处理库（如果需要）
    if (Object.keys(parsed.files).length > 0) {
      lines.push('const FormData = require(\'form-data\');');
      lines.push('const fs = require(\'fs\');');
    }
    
    lines.push('');
    
    // 构建配置对象
    const configParts = [];
    
    // Headers
    if (Object.keys(parsed.headers).length > 0) {
      configParts.push('  headers: {');
      for (const [key, value] of Object.entries(parsed.headers)) {
        configParts.push(`    '${key}': '${value}',`);
      }
      configParts.push('  },');
    }
    
    // Auth
    if (parsed.auth) {
      configParts.push('  auth: {');
      configParts.push(`    username: '${parsed.auth.username}',`);
      configParts.push(`    password: '${parsed.auth.password}',`);
      configParts.push('  },');
    }
    
    // Cookies
    if (Object.keys(parsed.cookies).length > 0) {
      const cookieString = Object.entries(parsed.cookies)
        .map(([name, value]) => `${name}=${value}`)
        .join('; ');
      if (configParts.length === 0) {
        configParts.push('  headers: {');
        configParts.push(`    'Cookie': '${cookieString}',`);
        configParts.push('  },');
      } else {
        // 添加到现有 headers
        const headerIndex = configParts.findIndex(line => line.includes('headers: {'));
        if (headerIndex >= 0) {
          configParts.splice(headerIndex + 1, 0, `    'Cookie': '${cookieString}',`);
        }
      }
    }
    
    // 构建请求数据
    let dataVariable = null;
    if (parsed.isMultipart && (Object.keys(parsed.files).length > 0 || Object.keys(parsed.params).length > 0)) {
      lines.push('const formData = new FormData();');
      
      for (const [key, value] of Object.entries(parsed.params)) {
        lines.push(`formData.append('${key}', '${value}');`);
      }
      
      for (const [key, filePath] of Object.entries(parsed.files)) {
        lines.push(`formData.append('${key}', fs.createReadStream('${filePath}'));`);
      }
      
      lines.push('');
      dataVariable = 'formData';
    } else if (parsed.isJson && parsed.data) {
      lines.push('const data = ' + parsed.data + ';');
      lines.push('');
      dataVariable = 'data';
    } else if (parsed.isForm || Object.keys(parsed.params).length > 0) {
      lines.push('const data = {');
      for (const [key, value] of Object.entries(parsed.params)) {
        lines.push(`  '${key}': '${value}',`);
      }
      lines.push('};');
      lines.push('');
      dataVariable = 'data';
    } else if (parsed.data) {
      lines.push(`const data = '${parsed.data}';`);
      lines.push('');
      dataVariable = 'data';
    }
    
    // 构建配置对象
    if (configParts.length > 0) {
      lines.push('const config = {');
      lines.push(...configParts);
      lines.push('};');
      lines.push('');
    }
    
    // 构建请求
    const method = parsed.method.toLowerCase();
    let requestLine = `axios.${method}('${parsed.url}'`;
    
    // 添加数据参数
    if (dataVariable && (method === 'post' || method === 'put' || method === 'patch')) {
      requestLine += `, ${dataVariable}`;
    }
    
    // 添加配置参数
    if (configParts.length > 0) {
      requestLine += configParts.length > 0 ? ', config' : '';
    }
    
    requestLine += ')';
    
    lines.push(requestLine);
    lines.push('  .then(response => console.log(response.data))');
    lines.push('  .catch(error => console.error(error));');
    
    return lines.join('\n');
  },
  
  toGo: (curl) => {
    const parsed = parseCurlCommand(curl);
    
    const lines = [
      'package main',
      '',
      'import (',
      '    "fmt"',
      '    "net/http"',
      '    "io/ioutil"'
    ];
    
    if (parsed.data) {
      lines.splice(-1, 0, '    "strings"');
    }
    
    lines.push(')', '', 'func main() {');
    
    if (parsed.data) {
      if (parsed.isJson) {
        lines.push(`    data := strings.NewReader(\`${parsed.data}\`)`);
      } else {
        lines.push(`    data := strings.NewReader("${parsed.data}")`);
      }
      lines.push(`    req, err := http.NewRequest("${parsed.method}", "${parsed.url}", data)`);
    } else {
      lines.push(`    req, err := http.NewRequest("${parsed.method}", "${parsed.url}", nil)`);
    }
    
    lines.push('    if err != nil {', '        panic(err)', '    }');
    
    if (Object.keys(parsed.headers).length > 0) {
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`    req.Header.Set("${key}", "${value}")`);
      }
    }
    
    lines.push(
      '',
      '    client := &http.Client{}',
      '    resp, err := client.Do(req)',
      '    if err != nil {',
      '        panic(err)',
      '    }',
      '    defer resp.Body.Close()',
      '',
      '    body, err := ioutil.ReadAll(resp.Body)',
      '    if err != nil {',
      '        panic(err)',
      '    }',
      '',
      '    fmt.Println(string(body))',
      '}'
    );
    
    return lines.join('\n');
  },
  
  toPhp: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = ['<?php'];
    
    lines.push('$ch = curl_init();');
    lines.push(`curl_setopt($ch, CURLOPT_URL, "${parsed.url}");`);
    lines.push('curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);');
    
    if (parsed.method !== 'GET') {
      lines.push(`curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "${parsed.method}");`);
    }
    
    if (Object.keys(parsed.headers).length > 0) {
      lines.push('curl_setopt($ch, CURLOPT_HTTPHEADER, [');
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`    "${key}: ${value}",`);
      }
      lines.push(']);');
    }
    
    if (parsed.data) {
      lines.push(`curl_setopt($ch, CURLOPT_POSTFIELDS, '${parsed.data}');`);
    }
    
    lines.push('', '$response = curl_exec($ch);', 'curl_close($ch);', 'echo $response;', '?>');
    
    return lines.join('\n');
  },
  
  toJava: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [
      'import java.net.http.HttpClient;',
      'import java.net.http.HttpRequest;',
      'import java.net.http.HttpResponse;',
      'import java.net.URI;'
    ];
    
    if (parsed.data) {
      lines.push('import java.net.http.HttpRequest.BodyPublishers;');
    }
    
    lines.push('', 'public class Main {', '    public static void main(String[] args) throws Exception {');
    
    lines.push('        HttpClient client = HttpClient.newHttpClient();');
    lines.push('        HttpRequest.Builder builder = HttpRequest.newBuilder()');
    lines.push(`                .uri(URI.create("${parsed.url}"))`);
    
    if (Object.keys(parsed.headers).length > 0) {
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`                .header("${key}", "${value}")`);
      }
    }
    
    if (parsed.data) {
      lines.push(`                .${parsed.method}(BodyPublishers.ofString("${parsed.data}"));`);
    } else {
      lines.push(`                .${parsed.method}(HttpRequest.BodyPublishers.noBody());`);
    }
    
    lines.push(
      '        HttpRequest request = builder.build();',
      '',
      '        HttpResponse<String> response = client.send(request,',
      '                HttpResponse.BodyHandlers.ofString());',
      '',
      '        System.out.println(response.body());',
      '    }',
      '}'
    );
    
    return lines.join('\n');
  },
  
  toCSharp: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [
      'using System;',
      'using System.Net.Http;',
      'using System.Text;',
      'using System.Threading.Tasks;',
      '',
      'class Program',
      '{',
      '    static async Task Main(string[] args)',
      '    {',
      '        using HttpClient client = new HttpClient();'
    ];
    
    if (Object.keys(parsed.headers).length > 0) {
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`        client.DefaultRequestHeaders.Add("${key}", "${value}");`);
      }
    }
    
    if (parsed.method === 'GET') {
      lines.push(`        string response = await client.GetStringAsync("${parsed.url}");`);
    } else {
      if (parsed.data) {
        lines.push(`        var content = new StringContent("${parsed.data}", Encoding.UTF8, "application/json");`);
        lines.push(`        var response = await client.${parsed.method === 'POST' ? 'PostAsync' : 'PutAsync'}("${parsed.url}", content);`);
        lines.push('        string responseBody = await response.Content.ReadAsStringAsync();');
        lines.push('        Console.WriteLine(responseBody);');
      } else {
        lines.push(`        var response = await client.${parsed.method === 'POST' ? 'PostAsync' : 'DeleteAsync'}("${parsed.url}", null);`);
        lines.push('        string responseBody = await response.Content.ReadAsStringAsync();');
        lines.push('        Console.WriteLine(responseBody);');
      }
    }
    
    if (parsed.method === 'GET') {
      lines.push('        Console.WriteLine(response);');
    }
    
    lines.push('    }', '}');
    
    return lines.join('\n');
  },
  
  toRust: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [
      'use reqwest;',
      'use std::collections::HashMap;',
      'use tokio;',
      '',
      '#[tokio::main]',
      'async fn main() -> Result<(), Box<dyn std::error::Error>> {',
      '    let client = reqwest::Client::new();'
    ];
    
    let requestBuilder = `client.${parsed.method.toLowerCase()}("${parsed.url}")`;
    
    if (Object.keys(parsed.headers).length > 0) {
      lines.push('    let mut headers = HashMap::new();');
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`    headers.insert("${key}", "${value}");`);
      }
      requestBuilder += '.headers(headers)';
    }
    
    if (parsed.data) {
      if (parsed.isJson) {
        lines.push(`    let json_data = serde_json::json!(${parsed.data});`);
        requestBuilder += '.json(&json_data)';
      } else {
        lines.push(`    let body = "${parsed.data}";`);
        requestBuilder += '.body(body)';
      }
    }
    
    lines.push(`    let resp = ${requestBuilder}`);
    lines.push('        .send()');
    lines.push('        .await?');
    lines.push('        .text()');
    lines.push('        .await?;');
    lines.push('');
    lines.push('    println!("{}", resp);');
    lines.push('    Ok(())');
    lines.push('}');
    
    return lines.join('\n');
  },
  
  toRuby: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [
      'require \'net/http\'',
      'require \'uri\'',
      'require \'json\'',
      ''
    ];
    
    lines.push(`uri = URI('${parsed.url}')`);
    lines.push('http = Net::HTTP.new(uri.host, uri.port)');
    
    if (parsed.url.startsWith('https')) {
      lines.push('http.use_ssl = true');
    }
    
    if (parsed.method === 'GET') {
      lines.push('request = Net::HTTP::Get.new(uri)');
    } else {
      lines.push(`request = Net::HTTP::${parsed.method === 'POST' ? 'Post' : parsed.method.charAt(0) + parsed.method.slice(1).toLowerCase()}.new(uri)`);
    }
    
    if (Object.keys(parsed.headers).length > 0) {
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`request['${key}'] = '${value}'`);
      }
    }
    
    if (parsed.data) {
      lines.push(`request.body = '${parsed.data}'`);
    }
    
    lines.push('');
    lines.push('response = http.request(request)');
    lines.push('puts response.body');
    
    return lines.join('\n');
  },
  
  toSwift: (curl) => {
    const parsed = parseCurlCommand(curl);
    const lines = [
      'import Foundation',
      '',
      `let url = URL(string: "${parsed.url}")!`,
      'var request = URLRequest(url: url)'
    ];
    
    if (parsed.method !== 'GET') {
      lines.push(`request.httpMethod = "${parsed.method}"`);
    }
    
    if (Object.keys(parsed.headers).length > 0) {
      for (const [key, value] of Object.entries(parsed.headers)) {
        lines.push(`request.setValue("${value}", forHTTPHeaderField: "${key}")`);
      }
    }
    
    if (parsed.data) {
      if (parsed.isJson) {
        lines.push(`let jsonData = "${parsed.data}".data(using: .utf8)!`);
        lines.push('request.httpBody = jsonData');
      } else {
        lines.push(`request.httpBody = "${parsed.data}".data(using: .utf8)`);
      }
    }
    
    lines.push('');
    lines.push('let task = URLSession.shared.dataTask(with: request) { data, response, error in');
    lines.push('    if let error = error {');
    lines.push('        print("Error: \\(error)")');
    lines.push('        return');
    lines.push('    }');
    lines.push('    ');
    lines.push('    if let data = data {');
    lines.push('        print(String(data: data, encoding: .utf8) ?? "")');
    lines.push('    }');
    lines.push('}');
    lines.push('task.resume()');
    
    return lines.join('\n');
  }
};

function App() {
  const [curlCommand, setCurlCommand] = useState('')
  const [targetLanguage, setTargetLanguage] = useState('python')
  const [convertedCode, setConvertedCode] = useState('')
  const [error, setError] = useState('')

  // 支持的语言列表
  const languages = [
    { value: 'python', label: 'Python (requests)', converter: simpleCurlConverter.toPython },
    { value: 'javascript', label: 'JavaScript (fetch)', converter: simpleCurlConverter.toJavaScript },
    { value: 'nodejs', label: 'Node.js (axios)', converter: simpleCurlConverter.toNodeAxios },
    { value: 'go', label: 'Go', converter: simpleCurlConverter.toGo },
    { value: 'php', label: 'PHP (cURL)', converter: simpleCurlConverter.toPhp },
    { value: 'java', label: 'Java (HttpClient)', converter: simpleCurlConverter.toJava },
    { value: 'csharp', label: 'C#', converter: simpleCurlConverter.toCSharp },
    { value: 'rust', label: 'Rust', converter: simpleCurlConverter.toRust },
    { value: 'ruby', label: 'Ruby', converter: simpleCurlConverter.toRuby },
    { value: 'swift', label: 'Swift', converter: simpleCurlConverter.toSwift }
  ]

  // 示例 curl 命令
  const examples = [
    {
      name: 'Simple GET',
      command: 'curl https://api.github.com/users/octocat'
    },
    {
      name: 'POST with JSON',
      command: 'curl -X POST https://httpbin.org/post -H "Content-Type: application/json" -d \'{"name": "John", "age": 30}\''
    },
    {
      name: 'With Headers & Cookies',
      command: 'curl -H "Authorization: Bearer token123" -H "Accept: application/json" -b "session_id=abc123; user_pref=dark_mode" https://api.example.com/data'
    },
    {
      name: 'Form Data with Auth', 
      command: 'curl -X POST https://httpbin.org/post -u "username:password" -d "title=My Document" -d "category=docs"'
    },
    {
      name: 'Complex JSON + Cookies',
      command: `curl 'https://www.ynlaw.cn/api/get_comp' -H 'content-type: application/json;charset=UTF-8' -b 'sajssdk_2015_cross_ZQSensorsObjnew_user=1' --data-raw '{"view": "LawyerTeam", "compId": "c_static_001_P_51230-17243991258670"}'`
    }
  ]

  const handleConvert = async () => {
    try {
      setError('')
      const selectedLang = languages.find(lang => lang.value === targetLanguage)
      if (selectedLang && curlCommand.trim()) {
        const result = selectedLang.converter(curlCommand)
        setConvertedCode(result)
      } else {
        setConvertedCode('')
      }
    } catch (err) {
      setError('转换失败: ' + err.message)
      setConvertedCode('')
    }
  }

  // 输入变化时自动转换
  const handleInputChange = (value) => {
    setCurlCommand(value)
    // 延迟转换，避免频繁操作
    if (value.trim()) {
      const timeoutId = setTimeout(() => {
        try {
          setError('')
          const selectedLang = languages.find(lang => lang.value === targetLanguage)
          if (selectedLang) {
            const result = selectedLang.converter(value)
            setConvertedCode(result)
          }
        } catch (err) {
          setError('转换失败: ' + err.message)
          setConvertedCode('')
        }
      }, 500) // 500ms 延迟
      
      return () => clearTimeout(timeoutId)
    } else {
      setConvertedCode('')
      setError('')
    }
  }

  // 语言变化时自动转换
  const handleLanguageChange = (newLanguage) => {
    setTargetLanguage(newLanguage)
    if (curlCommand.trim()) {
      try {
        setError('')
        const selectedLang = languages.find(lang => lang.value === newLanguage)
        if (selectedLang) {
          const result = selectedLang.converter(curlCommand)
          setConvertedCode(result)
        }
      } catch (err) {
        setError('转换失败: ' + err.message)
        setConvertedCode('')
      }
    }
  }

  const copyToClipboard = async () => {
    const btn = document.querySelector('.copy-btn')
    const originalText = btn.textContent
    
    try {
      // 检查 Clipboard API 是否可用
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(convertedCode)
      } else {
        // 降级方案：使用传统的 execCommand 或创建临时 textarea
        await fallbackCopyTextToClipboard(convertedCode)
      }
      
      // 显示成功提示
      btn.textContent = '✓ 已复制!'
      btn.style.background = '#28a745'
      
      setTimeout(() => {
        btn.textContent = originalText
        btn.style.background = ''
      }, 2000)
    } catch (err) {
      console.error('复制失败:', err)
      // 尝试降级方案
      try {
        await fallbackCopyTextToClipboard(convertedCode)
        btn.textContent = '✓ 已复制!'
        btn.style.background = '#28a745'
        
        setTimeout(() => {
          btn.textContent = originalText
          btn.style.background = ''
        }, 2000)
      } catch (fallbackErr) {
        console.error('降级复制也失败:', fallbackErr)
        btn.textContent = '✗ 复制失败'
        btn.style.background = '#dc3545'
        
        setTimeout(() => {
          btn.textContent = originalText
          btn.style.background = ''
        }, 3000)
        
        // 显示手动复制提示
        showManualCopyDialog(convertedCode)
      }
    }
  }

  // 降级复制方案
  const fallbackCopyTextToClipboard = (text) => {
    return new Promise((resolve, reject) => {
      // 创建临时 textarea 元素
      const textArea = document.createElement('textarea')
      textArea.value = text
      
      // 设置样式使其不可见
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      textArea.style.opacity = '0'
      
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      try {
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (successful) {
          resolve()
        } else {
          reject(new Error('execCommand copy failed'))
        }
      } catch (err) {
        document.body.removeChild(textArea)
        reject(err)
      }
    })
  }

  // 显示手动复制对话框
  const showManualCopyDialog = (text) => {
    const modal = document.createElement('div')
    modal.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
    `
    
    const dialog = document.createElement('div')
    dialog.style.cssText = `
      background: white;
      padding: 2rem;
      border-radius: 8px;
      max-width: 500px;
      width: 90%;
      max-height: 80%;
      overflow: auto;
    `
    
    dialog.innerHTML = `
      <h3 style="margin-top: 0; color: #333;">📋 手动复制代码</h3>
      <p style="color: #666; margin-bottom: 1rem;">自动复制失败，请手动选择并复制以下代码：</p>
      <textarea readonly style="
        width: 100%;
        height: 200px;
        font-family: monospace;
        font-size: 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 8px;
        resize: vertical;
      ">${text}</textarea>
      <div style="text-align: right; margin-top: 1rem;">
        <button onclick="this.parentElement.parentElement.parentElement.remove()" style="
          background: #6c757d;
          color: white;
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          cursor: pointer;
        ">关闭</button>
      </div>
    `
    
    modal.appendChild(dialog)
    document.body.appendChild(modal)
    
    // 选中文本
    const textarea = dialog.querySelector('textarea')
    textarea.focus()
    textarea.select()
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove()
      }
    })
  }

  const loadExample = (command) => {
    setCurlCommand(command)
    // 加载示例后自动转换
    try {
      setError('')
      const selectedLang = languages.find(lang => lang.value === targetLanguage)
      if (selectedLang) {
        const result = selectedLang.converter(command)
        setConvertedCode(result)
      }
    } catch (err) {
      setError('转换失败: ' + err.message)
      setConvertedCode('')
    }
  }

  const getSyntaxLanguage = () => {
    const syntaxMap = {
      'python': 'python',
      'javascript': 'javascript',
      'nodejs': 'javascript',
      'go': 'go',
      'php': 'php',
      'java': 'java',
      'csharp': 'csharp',
      'rust': 'rust',
      'ruby': 'ruby',
      'swift': 'swift'
    }
    return syntaxMap[targetLanguage] || 'text'
  }

  return (
    <div className="app">
      <header className="header">
        <h1>🔄 Curl Converter</h1>
        <p>将 curl 命令转换为各种编程语言的代码</p>
      </header>

      <main className="main">
        <div className="container">
          {/* 示例命令 */}
          <section className="examples">
            <h3>📝 示例命令</h3>
            <div className="example-buttons">
              {examples.map((example, index) => (
                <button
                  key={index}
                  className="example-btn"
                  onClick={() => loadExample(example.command)}
                >
                  {example.name}
                </button>
              ))}
            </div>
          </section>

          {/* 主工作区域 - 左右布局 */}
          <div className="main-workspace">
            {/* 输入区域 */}
            <section className="input-section">
              <div className="input-header">
                <h3>📥 输入 curl 命令</h3>
                <select
                  value={targetLanguage}
                  onChange={(e) => handleLanguageChange(e.target.value)}
                  className="language-select"
                >
                  {languages.map(lang => (
                    <option key={lang.value} value={lang.value}>
                      {lang.label}
                    </option>
                  ))}
                </select>
              </div>
              <textarea
                value={curlCommand}
                onChange={(e) => handleInputChange(e.target.value)}
                placeholder="粘贴你的 curl 命令..."
                className="curl-input"
                rows={12}
              />
              <div className="input-actions">
                <button onClick={handleConvert} className="convert-btn">
                  🔄 手动转换
                </button>
                <span className="auto-convert-hint">
                  ✨ 输入完成后自动转换
                </span>
              </div>
            </section>

            {/* 输出区域 */}
            <section className="output-section">
              <div className="output-header">
                <h3>📤 转换结果</h3>
              </div>
              
              {error && (
                <div className="error">
                  ❌ {error}
                </div>
              )}
              
              {convertedCode && (
                <div className="code-output">
                  <SyntaxHighlighter
                    language={getSyntaxLanguage()}
                    style={tomorrow}
                    customStyle={{
                      margin: 0,
                      borderRadius: '8px',
                      fontSize: '14px',
                      height: '100%'
                    }}
                  >
                    {convertedCode}
                  </SyntaxHighlighter>
                </div>
              )}
              
              {!convertedCode && !error && (
                <div className="placeholder">
                  ✨ 在左侧输入 curl 命令，结果将在这里显示
                </div>
              )}
              
              {/* 复制按钮放在输出框下方 */}
              {convertedCode && (
                <div className="output-actions">
                  <button onClick={copyToClipboard} className="copy-btn">
                    📋 复制代码
                  </button>
                </div>
              )}
            </section>
          </div>
        </div>
      </main>

      <footer className="footer">
        <p>基于 <a href="https://github.com/curlconverter/curlconverter" target="_blank" rel="noopener noreferrer">curlconverter</a> 构建</p>
      </footer>
    </div>
  )
}

export default App
